package com.cxh.rmsq.utils;

import static com.blankj.utilcode.util.ThreadUtils.runOnUiThread;

import android.app.DownloadManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Debug;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.util.Patterns;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import android.content.ClipData;
import android.content.ClipboardManager;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.regex.Pattern;

/**
 * @author pengbo
 * @date 2019/1/5 0005
 */
public class MyUtils {
    private static long lastClickTime;

    public static void moveToMiddle(RecyclerView recyclerView, int position) {
        //先从RecyclerView的LayoutManager中获取当前第一项和最后一项的Position
        int firstItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
        int lastItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
        //中间位置
        int middle = (firstItem + lastItem) / 2;
        // 取绝对值，index下标是当前的位置和中间位置的差，下标为index的view的top就是需要滑动的距离
        int index = (position - middle) >= 0 ? position - middle : -(position - middle);
        //左侧列表一共有getChildCount个Item，如果>这个值会返回null，程序崩溃，如果>getChildCount直接滑到指定位置,或者,都一样啦
        if (index >= recyclerView.getChildCount()) {
            recyclerView.scrollToPosition(position);
        } else {
            //如果当前位置在中间位置上面，往下移动，这里为了防止越界
            if (position < middle) {
                recyclerView.scrollBy(0, -recyclerView.getChildAt(index).getTop());
                // 在中间位置的下面，往上移动
            } else {
                recyclerView.scrollBy(0, recyclerView.getChildAt(index).getTop());
            }
        }
    }

    public static String calculate(String month, String day) {
        int m = Integer.parseInt(month);
        int d = Integer.parseInt(day);
        String name1 = "";
        if (m > 0 && m < 13 && d > 0 && d < 32) {
            if ((m == 3 && d > 20) || (m == 4 && d < 21)) {
                name1 = "白羊座 (Aries)";
            } else if ((m == 4 && d > 20) || (m == 5 && d < 21)) {
                name1 = "金牛座 (Taurus)";
            } else if ((m == 5 && d > 20) || (m == 6 && d < 22)) {
                name1 = "双子座 (Gemini)";
            } else if ((m == 6 && d > 21) || (m == 7 && d < 23)) {
                name1 = "巨蟹座 (Cancer)";
            } else if ((m == 7 && d > 22) || (m == 8 && d < 23)) {
                name1 = "狮子座 (Leo)";
            } else if ((m == 8 && d > 22) || (m == 9 && d < 23)) {
                name1 = "处女座 (Virgo)";
            } else if ((m == 9 && d > 22) || (m == 10 && d < 23)) {
                name1 = "天枰座 (Libra)";
            } else if ((m == 10 && d > 22) || (m == 11 && d < 22)) {
                name1 = "天蝎座 (Scorpio)";
            } else if ((m == 11 && d > 21) || (m == 12 && d < 22)) {
                name1 = "射手座 (Sagittarius)";
            } else if ((m == 12 && d > 21) || (m == 1 && d < 20)) {
                name1 = "摩羯座 (Capricorn)";
            } else if ((m == 1 && d > 19) || (m == 2 && d < 19)) {
                name1 = "水瓶座 (Aquarius)";
            } else if ((m == 2 && d > 18) || (m == 3 && d < 21)) {
                name1 = "双鱼座 (Pisces)";
            }

        } else {
            name1 = "您输入的生日格式不正确或者不是真实生日！";
        }
        return name1;
    }

    /**
     * 为防止多次重复点击
     *
     * @return
     */
    public static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 2000) {
            Log.e("fastClick", "不能点击过快");
            return true;
        }
        lastClickTime = time;
        return false;
    }


    public static int calculateAge(int birthYear, int birthMonth, int birthDay) {
        Calendar birthDate = Calendar.getInstance();
        birthDate.set(birthYear, birthMonth, birthDay);

        Calendar currentDate = Calendar.getInstance();

        if (birthDate.after(currentDate)) {
            throw new IllegalArgumentException("Birthdate is in the future!");
        }

        int age = currentDate.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);
        if (currentDate.get(Calendar.MONTH) < birthDate.get(Calendar.MONTH) ||
                (currentDate.get(Calendar.MONTH) == birthDate.get(Calendar.MONTH) &&
                        currentDate.get(Calendar.DAY_OF_MONTH) < birthDate.get(Calendar.DAY_OF_MONTH))) {
            age--; // 如果生日还没到，年龄减1
        }
        return age;
    }


    public static int calculateAge2(int birthYear, int birthMonth, int birthDay) {
        LocalDate birthDate = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            birthDate = LocalDate.of(birthYear, birthMonth, birthDay);
            LocalDate currentDate = LocalDate.now();
            if (birthDate.isAfter(currentDate)) {
                throw new IllegalArgumentException("Birthdate is in the future!");
            }
            return Period.between(birthDate, currentDate).getYears();
        }
        return birthYear;
    }

    /**
     * 转换为list
     */
    public static List<String> toList(String data) {
        List<String> numbersList = new ArrayList<>(Arrays.asList(data.split(",")));
        return numbersList;
    }


    // 检测调试器特征
    public static boolean isDebuggerConnected() {
        return Debug.isDebuggerConnected() /*||
                SystemProperties.get("ro.debuggable").equals("1")*/;
    }

    // 检测Xposed框架
    public static boolean checkXposed() {
        try {
            Class.forName("de.robv.android.xposed.XposedBridge");
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 获取视频的第一帧并显示在ImageView上
     *
     * @param context   上下文
     * @param videoPath 视频路径
     * @param imageView 用于显示缩略图的ImageView
     */
    public static void getVideoThumbnail(Context context, String videoPath, ImageView imageView) throws IOException {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(videoPath);
            // 获取第一帧（单位为微秒，0表示第一帧）
            Bitmap bitmap = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
            // 显示在ImageView上
            imageView.setImageBitmap(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
    }

    public static void playVideoFromFile(Context context, String filename, VideoView video) {

        File file = new File(filename);
        MediaController media = new MediaController(context);

//        if (file.exists()) {
        //将VideoView与MediaController进行关联
//            video.setVideoPath(file.getAbsolutePath());
        video.setVideoURI(Uri.parse(filename));
        video.invalidate();
        video.setMediaController(media);
        media.setMediaPlayer(video);
        //让VideoView获取焦点
        video.requestFocus();
        video.start();
//            startCard.setText(R.string.pauseCard);
//            fileName.setText(filename);
//        }
//    } else {
//        video.pause();
//        startCard.setText(R.string.startCard);
//    }
    }


    /**
     * copy文本
     *
     * @return
     */
    public static void copyTextToClipboard(Context context, String text) {
        // 获取系统服务来获取ClipboardManager
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);

        // 创建一个ClipData对象，包括要复制的文本
        ClipData clip = ClipData.newPlainText("label", text);

        // 设置剪贴板内容
        clipboard.setPrimaryClip(clip);
    }


    /**
     * 获取IP
     *
     * @return
     */
    public static String getLocalIpAddress() {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) { // 排除回环地址
                        return addr.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static Bitmap getBitmapFromURL(String src) {
        try {
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(input);
            input.close();
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void saveBitmapToGallery(Context context, Bitmap bitmap, String fileName) {
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10+ 使用 MediaStore
            values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
            ContentResolver resolver = context.getContentResolver();
            Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            if (uri != null) {
                try (OutputStream outputStream = resolver.openOutputStream(uri)) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            // Android 9 及以下直接保存到 Pictures 目录
            File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            File imageFile = new File(picturesDir, fileName);
            try (FileOutputStream fos = new FileOutputStream(imageFile)) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                // 通知系统更新相册
                MediaScannerConnection.scanFile(context,
                        new String[]{imageFile.getAbsolutePath()}, null, null);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void downloadImage(Context context, String imageUrl) {
        new Thread(() -> {
            try {
                // 创建 HTTP 连接
                URL url = new URL(imageUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                // 获取输入流
                InputStream inputStream = connection.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                // 保存到本地
                MyUtils.saveBitmapToGallery(context, bitmap, "my_image_" + System.currentTimeMillis() + ".jpg");

                // 提示成功
                runOnUiThread(() -> Toast.makeText(context, "图片已保存", Toast.LENGTH_SHORT).show());

            } catch (IOException e) {
                e.printStackTrace();
                runOnUiThread(() -> Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show());
            }
        }).start();
    }

    public static void downloadFromNetwork(Context context, String url) {
        // 使用 DownloadManager 或 OkHttp 下载
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setTitle("视频下载中");
        request.setDescription(url.substring(url.lastIndexOf("/") + 1));
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "video_" + System.currentTimeMillis() + ".mp4");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        manager.enqueue(request);
        Toast.makeText(context, "开始下载视频", Toast.LENGTH_SHORT).show();
    }

    public static Bitmap generateQRCode(String text, int size) throws WriterException {
        BitMatrix bitMatrix;
        try {
            bitMatrix = new MultiFormatWriter().encode(
                    text,
                    BarcodeFormat.QR_CODE,
                    size,
                    size,
                    null
            );
        } catch (IllegalArgumentException e) {
            return null;
        }

        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF;
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }

    public static boolean isAlipayAccount(String input) {
        input = input.trim();
        // 手机号正则（11位，1开头，第二位3-9）
        Pattern phonePattern = Pattern.compile("^1[3-9]\\d{9}$");
        // 邮箱正则（简单版本）
        Pattern emailPattern = Pattern.compile("^[\\w.%+-]+@[\\w.-]+\\.[a-zA-Z]{2,}$");
        return phonePattern.matcher(input).matches() || emailPattern.matcher(input).matches();
    }

    public static boolean isWechatAccount(String input) {
        input = input.trim();
        // 手机号或邮箱
        Pattern phoneEmailPattern = Pattern.compile("^(1[3-9]\\d{9}|[\\w.%+-]+@[\\w.-]+\\.[a-zA-Z]{2,})$");
        // 自定义ID正则（字母开头，6-20位）
        Pattern customIdPattern = Pattern.compile("^[a-zA-Z][-_a-zA-Z0-9]{5,19}$");
        return phoneEmailPattern.matcher(input).matches() || customIdPattern.matcher(input).matches();
    }

    public static boolean isValidUrl(String input) {
        input = input.trim();
        // 使用Android内置检查
        boolean isWebUrl = Patterns.WEB_URL.matcher(input).matches();
        // 自定义检查，确保包含域名和协议（可选）
        Pattern strictUrlPattern = Pattern.compile("^(https?://)?([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,}(/\\S*)?$");
        return isWebUrl && strictUrlPattern.matcher(input).matches();
    }
}
